using System.Data.SqlClient;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace Lib.Db {
    public interface IDbProvider {
        SqlConnection Get ();
    }

    public class DapperDbProvider : IDbProvider {
        private readonly IConfiguration _configuration;
        private readonly ILogger _logger;
        private SqlConnection _connection;

        public DapperDbProvider (IConfiguration configuration, ILoggerFactory loggerFactory) {
            _configuration = configuration;
            _logger = loggerFactory.CreateLogger<DapperDbProvider> ();
        }

        public SqlConnection Get () {
            if (_connection == null) {
                var connString = _configuration.GetConnectionString ("dev");
                _logger.LogDebug ($"DevConnection: {connString}");
                _connection = new SqlConnection (connString);
            }

            _logger.LogDebug($"ConnectionHash: {_connection.GetHashCode()}");

            return _connection;
        }
    }
}